/**
 * 物品
 */
const Router = require('@koa/router');
const { Map } = require('../db/schemas')

const { Language } = require('../env');
const { genResponse, raw$project } = require('../utils');
const { paginationCheck } = require('../middlewares/index');

const router = new Router({ prefix: '/map', strict: false })

function escapeRegExp(keyword) {
  return keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

router.get('/', async (ctx) => {
  const { current, pageSize, keyword = '' } = ctx.query;

  const page = parseInt(current);
  const page_size = parseInt(pageSize);

  const trimmedKeyword = keyword.trim();
  const escapedKeyword = trimmedKeyword ? escapeRegExp(trimmedKeyword) : '';

  const searchQuery = trimmedKeyword
    ? { name: { $regex: escapedKeyword, $options: 'i' } }
    : {};

  const sort = { create_at: -1 };

  const aggregationPipeline = [
    { $match: searchQuery },
    { $sort: sort },
    {
      $facet: {
        results: [
          { $skip: (page - 1) * page_size },
          { $limit: page_size }
        ],
        total: [
          { $count: 'total' }
        ]
      }
    }
  ];
  const aggregationResult = await Map.aggregate(aggregationPipeline)

  const results = aggregationResult[0].results; // 分页数据
  const total = aggregationResult[0].total[0]?.total || 0; // 总数（可能为0）
  const totalPages = Math.ceil(total / page_size); // 总页数

  ctx.body = genResponse(true, { results, total, totalPages })
})

router.post('/', async (ctx) => {
  if (ctx.request.body instanceof Array) {
    const mapIDs = ctx.request.body.map(m => m.mapID)
    const existingIDs = await Map.find({ mapID: { $in: mapIDs } }, { mapID: 1 }).lean()
    const existingSet = new Set(existingIDs.map(r => r.mapID));
    const validRecords = ctx.request.body.filter(m => !existingSet.has(m.mapID))
    const results = await Map.insertMany(validRecords)
    ctx.body = genResponse(true, {
      success: results.length,
      duplicates: existingSet.size,
    })
  } else {
    const record = await Map.findOne({ mapID: parseInt(ctx.request.body.mapID) })
    if (record) {
      ctx.throw(400, '记录已存在')
    }
    const doc = new Map(ctx.request.body)
    await doc.save()
    ctx.body = genResponse(true, doc)
  }
})

router.put('/:mapID', async (ctx) => {
  const mapID = parseInt(ctx.request.body.mapID || ctx.params.mapID)
  const record = await Map.findOneAndUpdate({ mapID }, ctx.request.body)
  ctx.body = genResponse(true, record)
})

router.delete('/:mapID', async (ctx) => {
  const mapID = parseInt(ctx.params.mapID)
  const record = await Map.findOneAndDelete({ mapID: mapID })
  ctx.body = genResponse(true, record)
})

module.exports = router